package scau.zxck.utils;

import java.io.*;

/**
 * Created by lsp on 27/11/2016.
 */
public class FileUtil {
    /**
     * 从文件中读取内容，按照原格式，一行一行(换行)
     *
     * @param filePath 文件的绝对路径
     * @return
     */
    public static String readContentFromFile(String filePath) {
        BufferedReader reader = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
                stringBuffer.append(newLine());
            }
            reader.close();
            return stringBuffer.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 把指定内容写入文件
     *
     * @param filePath 文件绝对路径
     * @param content  内容
     * @return
     */
    public static Boolean writeContentToFile(String filePath, String content) {
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(new
                    FileOutputStream(filePath)));
            writer.write(content);
            writer.close();
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void createDirIfNotExists(String path){
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
    }

    public static String newLine() {
        return java.security.AccessController.doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
    }
}
